//
//  CarnivalsDetailViewController.m
//  PartyAnimal
//
//  Created by Hilary Muludiang on 3/13/12.
//  Copyright 2012 Muludiang. All rights reserved.
//

#import "CarnivalsDetailViewController.h"
#import "PartyAnimalAppDelegate.h"
#import "iBacchanal.h"
#import "StackMob.h"

@implementation CarnivalsDetailViewController

@synthesize countryFlag;
@synthesize cityStateCountry;
@synthesize website;
@synthesize phoneNumber;
@synthesize startDate;
@synthesize endDate;
@synthesize carnivalTitle;
@synthesize bkgdView;
@synthesize contentView;
@synthesize detailsScroller;

-(void)getCarnivalDetails{
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	NSLog(@"%@", bacchanal.currentUser);
	for (NSDictionary *carnival in bacchanal.carnivalsData)
	{
		if ([[carnival objectForKey:@"carnivals_id"] isEqualToString: bacchanal.carnivalID]) {
			
			self.navigationItem.title = [carnival objectForKey:@"city"];
			
			NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier: @"en_US"] autorelease];
			NSArray *countryArray = [NSLocale ISOCountryCodes];
			for (NSString *countryCode in countryArray) 
			{
				NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
				
				if ([[locale displayNameForKey:NSLocaleCountryCode value:countryCode] isEqualToString: [carnival objectForKey:@"country"]]){
					[countryFlag setImage:[UIImage imageNamed:[NSString stringWithFormat: @"%@.png", [countryCode lowercaseString] ]]];
					//NSLog(@"ISOCodes %@|Country %@", countryCode, [carnival objectForKey:@"country"]);
				}
				[pool release];
			}
			//carnivalsDetail.text = [carnival description];
			if ([[carnival objectForKey:@"carnivalTitle"] length] > 0)
				carnivalTitle.text = [carnival objectForKey:@"carnivalTitle"];
			else
				carnivalTitle.text = [NSString stringWithFormat:@"%@ Carnival", [carnival objectForKey:@"city"]];
			
			if ([[carnival objectForKey:@"state"] length] > 0)
				cityStateCountry.text = [NSString stringWithFormat:@"%@ - %@, %@", [carnival objectForKey:@"city"], [carnival objectForKey:@"state"], [carnival objectForKey:@"country"]];
			else
				cityStateCountry.text = [NSString stringWithFormat:@"%@, %@", [carnival objectForKey:@"city"], [carnival objectForKey:@"country"]];
			
			startDate.text = [carnival objectForKey:@"startDate"];
			endDate.text = [carnival objectForKey:@"endDate"];
			
			if ([[carnival objectForKey:@"website"] length] > 0)
				website.titleLabel.text = [carnival objectForKey:@"website"];
			
			if ([[carnival objectForKey:@"phoneNumber"] length] > 0)
				phoneNumber.titleLabel.text = [carnival objectForKey:@"phoneNumber"];
			
			if ([bacchanal.currentUser isEqualToString:[carnival objectForKey:@"submittedBy"]])
			self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"trash_can_30"] style:UIBarButtonItemStyleBordered target:self action:@selector(deleteCarnival:)] autorelease];											  

		}
	}
}


-(IBAction)launchFeedback {
    [TestFlight openFeedbackView];
}

-(IBAction)deleteCarnival:(UIButton *)sender{
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	//NSString *idValue = "@johndoe" // some primary key value for the object you want to update
	NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1], @"hidden", nil];
	[[StackMob stackmob] put:@"carnivals" withId:bacchanal.carnivalID andArguments:args andCallback:^(BOOL success, id result) {
		if (success) {
			// update successful, cast result to 
			// NSDictionary if necessary
			UIAlertView *submitAlert = [[UIAlertView alloc] initWithTitle:nil message:@"Carnival information successfully deleted." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[submitAlert show];
			
		} else {
			NSLog(@"%@", result);
			// update failed
		}
	}];
	
	
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	bacchanal.dataChanged = YES;
	
	[self.navigationController  popViewControllerAnimated:YES];	
	[alertView release];
}

// Helper function to size views
- (void)fixupAdView:(UIInterfaceOrientation)toInterfaceOrientation {
 	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.adBannerView  != nil) {        
        if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
            [bacchanal.adBannerView  setCurrentContentSizeIdentifier:
			 ADBannerContentSizeIdentifierLandscape];
        } else {
            [bacchanal.adBannerView  setCurrentContentSizeIdentifier:
			 ADBannerContentSizeIdentifierPortrait];
        }          
        [UIView beginAnimations:@"fixupViews" context:nil];
        if (bacchanal.adBannerViewIsVisible) {
            CGRect adBannerViewFrame = [bacchanal.adBannerView  frame];
            adBannerViewFrame.origin.x = 0;
            adBannerViewFrame.origin.y = 0;
            [bacchanal.adBannerView  setFrame:adBannerViewFrame];
            CGRect contentViewFrame = contentView.frame;
            contentViewFrame.origin.y = [bacchanal getBannerHeight:toInterfaceOrientation];
            contentViewFrame.size.height = self.view.frame.size.height - [bacchanal getBannerHeight:toInterfaceOrientation];
            contentView.frame = contentViewFrame;
			bkgdView.frame = contentViewFrame;
        } else {
			[self hideBanner:toInterfaceOrientation];
        }
        [UIView commitAnimations];
    }   
}

-(void)hideBanner:(UIInterfaceOrientation)toInterfaceOrientation{
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	CGRect adBannerViewFrame = [bacchanal.adBannerView frame];
	adBannerViewFrame.origin.x = 0;
	adBannerViewFrame.origin.y = - [bacchanal getBannerHeight:toInterfaceOrientation];
	[bacchanal.adBannerView  setFrame:adBannerViewFrame];
	CGRect contentViewFrame = contentView.frame;
	contentViewFrame.origin.y = 0;
	contentViewFrame.size.height = self.view.frame.size.height + [bacchanal getBannerHeight:toInterfaceOrientation];
	contentView.frame = contentViewFrame;            
 	bkgdView.frame = contentViewFrame;
}

// Implement AdBannerViewDelegate
#pragma mark ADBannerViewDelegate

- (void)bannerViewDidLoadAd:(ADBannerView *)banner {
   	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (!bacchanal.adBannerViewIsVisible) {                
        bacchanal.adBannerViewIsVisible = YES;
        [self fixupAdView:[UIDevice currentDevice].orientation];
    }
}

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error{
   	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.adBannerViewIsVisible)
    {        
        bacchanal.adBannerViewIsVisible = NO;
        [self fixupAdView:[UIDevice currentDevice].orientation];
    }
}


// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 
 }*/



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.bkgdView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"iBacchanalbkgd.png"]];
	self.bkgdView.alpha = 0.125;
	self.contentView.backgroundColor = [UIColor clearColor];
	self.detailsScroller.contentSize = CGSizeMake(self.view.frame.size.width, 450);


}



-(void)viewWillAppear:(BOOL)animated{
	[TestFlight passCheckpoint:@"Viewing Carnival Details"];

	[super viewWillAppear:YES];
	// NSLog(@"%@|%@|%@|%@", passedValue, selectedCity, carnivalDate, selectedView);
	//self.detailsScroller.contentSize = self.detailsScroller.frame.size;
	[self getCarnivalDetails];
	[self.view addSubview:[[iBacchanal sharedUser] adBannerView] ];

	[self fixupAdView:[UIDevice currentDevice].orientation];
}

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	[self hideBanner:[UIDevice currentDevice].orientation];
	[bacchanal.adBannerView removeFromSuperview];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return YES; // (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[detailsScroller release];
	[contentView release];
	[carnivalTitle release];
	[startDate release];
	[endDate release];
	[cityStateCountry release];
	[website release];
	[phoneNumber release];
	[countryFlag release];
	[bkgdView release];
    [super dealloc];
}


@end
